package xyz.fefine;

/**
 * Created by feng_ on 2016/9/17.
 */
public class ArrayEnv implements Enviorment {

    protected Object[] values;
    protected Enviorment outer;

    public ArrayEnv(int size, Enviorment outer) {
        this.values = new Object[size];
        this.outer = outer;
    }


    @Override
    public Object get(int nest, int index) {

        if (nest == 0) {
            return values[index];
        } else if (outer == null) {
            return null;
        }
        return outer.get(nest - 1, index);
    }

    @Override
    public Symbols symbols() {
        throw new StoneException("no symbols");
    }


    @Override
    public void put(int nest, int index, Object value) {
        if (nest == 0) {
            values[index] = value;
        } else if (outer == null) {
            throw new StoneException("no outer environment");
        } else {
            outer.put(nest - 1, index, value);
        }
    }




    /***********************never use***************************/

    @Override
    public void put(String name, Object value) {
        error(name);
    }

    @Override
    public Object get(String name) {

        if (outer != null) {
            return outer.get(name);
        }

        error(name);
        return null;
    }

    @Override
    public void setOuter(Enviorment outer) {
        this.outer = outer;
    }

    @Override
    public void putNew(String name, Object value) {
        error(name);
    }

    @Override
    public Enviorment where(String name) {
        error(name);
        return null;
    }


    private void error(String name) {
        throw new StoneException("cannot access by name: " + name);
    }

}
